package com.webside.points.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.webside.points.model.AnswerEntity;
import com.webside.points.model.ExpertEntity;
import com.webside.points.model.IssueEntity;
import com.webside.points.model.UserEntity;
import com.webside.points.service.AdvertisingService;
import com.webside.points.service.AnswerService;
import com.webside.points.service.ExpertService;
import com.webside.points.service.IssueService;
import com.webside.points.service.IssueTypeService;
import com.webside.points.service.LikeService;
import com.webside.points.service.UserService;
import com.webside.points.wechat.Constant;
import com.webside.points.wechat.PageUtil;
import com.webside.points.wechat.Util;
import com.webside.points.wechat.WeChatConfig;
import com.webside.points.wechat.Wechat;

@Controller
@Scope("prototype")
@RequestMapping("/issue/")
public class IssueContronller {

	@Autowired
	IssueService issueService ;
	
	@Autowired
	UserService userService;
	
	@Autowired
	ExpertService expertService;
	
	@Autowired
	IssueTypeService issueTypeService;
	
	@Autowired
	LikeService likeService;
	
	@Autowired
	AnswerService answerService;
	
	@Autowired
	AdvertisingService advertisingService;
	
	
	@RequestMapping("findAllUI")
	public String findAllUI(Model model){
		
		PageUtil pageUtil=new PageUtil();
		  //总记录数
		  IssueEntity issueEntity=new IssueEntity();
		  int totalCount=issueService.findCount(issueEntity);
		  pageUtil.setTotalCount(totalCount);
		  pageUtil.setCurPage(1);
		  model.addAttribute("pageUtil", pageUtil);
		  model.addAttribute("issueType", issueTypeService.findAll());
		return "serve/issue";
	}
	
	@RequestMapping("findAll")
	public void findAll(IssueEntity issueEntity,Model model,HttpServletResponse response) throws Exception{
		 
		System.out.println("进入查询问题：>>>"+issueEntity);
		PageUtil pageUtil=new PageUtil();
		 
		 if(String.valueOf(issueEntity.getCurPage())!=null){
			 int cPage=Integer.valueOf(issueEntity.getCurPage());
			 pageUtil.setCurPage(cPage);
			 cPage=(cPage-1)*10;
			 issueEntity.setCurPage(Integer.valueOf(cPage));
		 }
		List<IssueEntity> list = issueService.findAll(issueEntity);
		// int totalCount=issueService.findCount(issueEntity);
		  pageUtil.setContent(list);
		 // pageUtil.setTotalCount(totalCount);
		  model.addAttribute("pageUtil", pageUtil);
		  
		String json = JSON.toJSONString(pageUtil);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
	  }
	
	
	@RequestMapping("insert")
	public String insert (IssueEntity issueEntity,String expert,String openId,Model model){
		System.out.println(issueEntity+"   "+expert);
		UserEntity userEntity=userService.findByOpenId(openId);
		
		if(userEntity.getStatus().equals("1")){
			
			
			issueEntity.setUserId(userEntity.getId());
			issueEntity.setCreateTime(new Date(System.currentTimeMillis()));
			issueEntity.setStatus("1");
			if(expert!=null){
				issueEntity.setExpertIssueId(expert);
			}
			int result = issueService.insert(issueEntity);
			if(result==1){
				IssueEntity issue = issueService.findById(issueEntity.getId());
				
				List<ExpertEntity> list=null;
				if(expert!=null){
					list=new ArrayList<ExpertEntity>();
					ExpertEntity expertEntity =  expertService.findById(Integer.valueOf(expert));
					list.add(expertEntity);
					System.out.println("list>>>:"+list);
				}else{
					list= expertService.findByExpertTypeId(issueEntity.getIssueTypeId());
				}
				
				for(int i=0;i<list.size();i++){
					//不发给已停用的专家
					if(list.get(i).getUserEntity().getStatus().equals("1")){
						String touser=list.get(i).getUserEntity().getOpenId();
						//不发送给自己
						if(!touser.equals(openId)){
							String url = Constant.REALM_URL +"service/character-issue.jsp?issueId="+issueEntity.getId()+"&openId="+touser+"&type=answer";
							System.out.println("url:>>>"+url);
							
							Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
							
							Map<String, String> first=new HashMap<String, String>();
							first.put("value", "用户提问成功通知。");
							first.put("color", WeChatConfig.MESSAGE_COLOR);
							
							Map<String, String> keyword1=new HashMap<String, String>();
							keyword1.put("value", issue.getIssueContent());
							keyword1.put("color", WeChatConfig.MESSAGE_COLOR);

							Map<String, String> keyword2=new HashMap<String, String>();
							if(issueEntity.getIssueTypeId().equals("1")){
								keyword2.put("value", "教法问题");
							}else if(issueEntity.getIssueTypeId().equals("2")){
								keyword2.put("value", "生活问题");
							}
							
							keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
							
							Map<String, String> remark=new HashMap<String, String>();
							remark.put("value", "用户急需你的帮助，请您尽快解答哦！");
							remark.put("color", WeChatConfig.MESSAGE_COLOR);
							
							data.put("first",first);
							data.put("keyword1",keyword1);
							data.put("keyword2",keyword2);
							data.put("remark",remark);
							
							Wechat.sendMessage(data,WeChatConfig.ISSUE_DISPOSE_NOTICE,touser,url);
						}
					}
					
				}
				
			}
			model.addAttribute("result", result);
			return "redirect:../issueType/findAll?mark=service&openId="+openId;
		}
		return "service/error";
		
	}
	
	@RequestMapping("findIssueRecordUI")
	public String findIssueRecordUI(Model model,String openId){
		UserEntity userEntity= userService.findByOpenId(openId);
		model.addAttribute("user", JSON.toJSONString(userEntity));
		
		return "service/issue-record";
	}
	
	@RequestMapping("findIssueRecord")
	public void findIssueRecord(int page,int size,String openId,HttpServletResponse response){
		
		UserEntity userEntity= userService.findByOpenId(openId);
		Map<String,Integer> map=new HashMap<String,Integer>();
		map.put("userId", userEntity.getId());
		if(page!=0){
			 int cPage=page;
			 cPage=(cPage-1)*10;
			 map.put("page", cPage);
			 map.put("size", size);
		 }
		System.out.println("map:>>>:"+map);
		List<IssueEntity> issueList=issueService.findRecord(map);
		
		
		String json = JSON.toJSONString(issueList);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
		
	}
	
	@RequestMapping("queryAnswerUI")
	public String queryAnswerUI(Model model,String openId){
		UserEntity userEntity= userService.findByOpenId(openId);
		System.out.println(userEntity+"   "+openId);
		model.addAttribute("user", JSON.toJSONString(userEntity));
		return "service/issue-answer";
	}
	
	@RequestMapping("queryAnswer")
	public void queryAnswer(int page,int size,String openId,HttpServletResponse response){
		System.out.println("审核专家："+page+"  "+size+"  "+openId);
		Map<String, Integer> map = new HashMap<String, Integer>();
		List<IssueEntity> list=null;
		UserEntity userEntity= userService.findByOpenId(openId);
		System.out.println(userEntity+"   "+openId);

		ExpertEntity expertEntity = expertService.findById(userEntity.getExpertId());
		if(expertEntity!=null){
			 if(page!=0){
				 int cPage=page;
				 cPage=(cPage-1)*10;
				 map.put("page", cPage);
				 map.put("size", size);
				 
			 }
			 System.out.println("map:>>>"+map);
			 //教法问题类可以抢答所有问题
			if(expertEntity.getExpertType().equals("1")){
				list = issueService.queryAnswer(map);
			}else{
				map.put("expertTypeId", Integer.valueOf(expertEntity.getExpertType()));
				list = issueService.queryAnswer(map);
			}
			System.out.println(expertEntity+" "+"list:>>>"+list);
		}

		String json = JSON.toJSONString(list);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
		
	}
	
	@RequestMapping("addIssue")
	public String addIssue(IssueEntity issueEntity){
		issueEntity.setAddCreateTime(new Date(System.currentTimeMillis()));
		issueService.addIssue(issueEntity);
		return "redirect:../issueType/findAll?mark=service";
	}
	
	@RequestMapping("findById")
	public String findById(int issueId,String openId,String mark,Model model,HttpServletRequest request){
		
		IssueEntity issueContent=issueService.findById(issueId);
		if(issueContent!=null){
			model.addAttribute("issueContent", issueContent);
			//List<AnswerEntity> answerList = answerService.findByIssueId(issueId);
			//System.out.println("answerList:>>>"+answerList);
			//model.addAttribute("answerList", answerList);
			
			IssueEntity issueEntity=new IssueEntity();
			issueEntity.setBrowseNumber(issueContent.getBrowseNumber()+1);
			issueEntity.setId(issueContent.getId());
			
			issueService.updateStatus(issueEntity);
			
			if(openId!=null&&!openId.equals("")){
				request.getSession().setAttribute("openId", openId);
			}
			
			String oId = (String) request.getSession().getAttribute("openId"); 
			UserEntity UserEntity = userService.findByOpenId(oId);
			model.addAttribute("user", UserEntity);
			
			model.addAttribute("mark", mark);
			
			model.addAttribute("issueCenter", advertisingService.findByLocation("issue-center"));
			model.addAttribute("issueBottom", advertisingService.findByLocation("issue-bottom"));
		}
		return "service/content";
	}
	
	@RequestMapping("findByIssue")
	public void findByIssue(int page,int size,int issueId,HttpServletResponse response){
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("issueId", issueId);
		if(page!=0){
			 int cPage=page;
			 cPage=(cPage-1)*10;
			 map.put("page", cPage);
			 map.put("size", size);
			 
		 }
		List<AnswerEntity> answerList = answerService.findByIssueId(map);
		
		String json = JSON.toJSONString(answerList);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
	}
	
	@RequestMapping("findCount")
	public void findCount(IssueEntity issueEntity,HttpServletResponse response){
		
		int count=issueService.findCount(issueEntity);
		String json = JSON.toJSONString(count);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
	}
	
	@RequestMapping("updateStatus")
	public String updateStatus(IssueEntity issueEntity){
		System.out.println(issueService.updateStatus(issueEntity));
		return "redirect:findAllUI";
	}
	
	@RequestMapping("findByIssueId")
	public void findByIssueId(int issueId,Model model,HttpServletResponse response) throws Exception{
		 
		System.out.println("进入查询问题：>>>"+issueId);
		
		IssueEntity issueEntity = issueService.findById(issueId);

		  
		String json = JSON.toJSONString(issueEntity);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
	  }
	
	@RequestMapping("issueSearch")
	public void issueSearch(int page,int size,String content,HttpServletResponse response){
		System.out.println("content:>>未加密"+content);
		List<IssueEntity> list =null;
		Map<String,Object> map = new HashMap<String, Object>();
		if(page!=0){
			 int cPage=page;
			 cPage=(cPage-1)*10;
			 map.put("page", cPage);
			 map.put("size", size);
			 
		 }
		if(content!=""){
			try {
				content = URLDecoder.decode(content , "UTF-8"); 
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} 
			content="%"+Util.getBase64(content)+"%";
			map.put("content", content);
			System.out.println("content:>>>加密后"+content);
			list = issueService.issueSearch(map);
		}
		System.out.println("list:>>>"+list);
		String json = JSON.toJSONString(list);
		try {
			response.getWriter().write(json);
			response.flushBuffer();
		} catch (Exception e) {
			System.out.println("JsonError："+e);
		}
	}
}
